package com.sobjal.android;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import com.sobjal.android.utils.SmartObjects;
import com.sobjal.android.xml.SendXml;
import com.sobjal.android.xml.XmlParser;
import com.sobjal.android.xml.XmlWriter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.view.View.OnClickListener;

/**
 * 
 * @author Fabio Monteiro, Lu Chen
 * 
 * Class to perform actions on the devices through XML calls to the server
 *
 */
public class Action extends Activity {
	private Bundle b;
	private HashMap<String, Object> selectedObject;
	
	public static final String PREFS_NAME = "MyPreferences";
	

	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.setTitle("Choose an action");

		//getting the previously selected SmartObject 
		b = getIntent().getExtras();
		selectedObject = (HashMap<String, Object>) b.getSerializable("selectedObject");

		//Toast.makeText(getApplicationContext(),(String) selectedObject.get("name"),Toast.LENGTH_SHORT).show();

		//setting the layout depending on the type of device	
		/**
		 * *************************************************************
		 * NABAZTAG
		 * *************************************************************
		 */	
		if(((String) selectedObject.get("deviceType")).equalsIgnoreCase("nabaztag")){
			setContentView(R.layout.action_nabaztag);

			//handling sending a message (Nabaztag)
			Button buttonSendMessage = (Button) findViewById(R.id.ButtonMessage);
			buttonSendMessage.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					// TODO Auto-generated method stub

					String text = ((EditText) findViewById(R.id.EditText01)).getText().toString();
					String name = (String) selectedObject.get("name");

					//writing xml
					String xml = XmlWriter.writeXmlForSendingMessage(
							(String) selectedObject.get("idDevice"), 
							text);

					//calling the webservice
					String xmlResponse = SendXml.sendXmlToServer(xml);

					ArrayList<String> temp = XmlParser.parseGeneralGetMsgAndComment(xmlResponse);
					String comment = temp.get(1);


					Toast.makeText(getApplicationContext(), name+": " + comment, Toast.LENGTH_SHORT).show();			
				}
			});

			//handling getting friends (Nabaztag)
			Button buttonGetFriends = (Button) findViewById(R.id.ButtonGetFriends);
			buttonGetFriends.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					//writing xml
					String xml = XmlWriter.writeXmlForGettingFriends((String) selectedObject.get("idDevice"));

					//calling the webservice
					String xmlResponse = SendXml.sendXmlToServer(xml);
					String name = (String) selectedObject.get("name");

					ArrayList<String> friendsList = new ArrayList<String>();

					friendsList = XmlParser.parseGetFriendsResponse(xmlResponse);

					if(friendsList.size()==0){
						Toast.makeText(getApplicationContext(), name+ " got no friends :(", Toast.LENGTH_SHORT).show();

					}else{

						Iterator i = friendsList.iterator();
						while(i.hasNext()){
							Toast.makeText(getApplicationContext(), name+ "'s friend : "+(String) i.next(), Toast.LENGTH_SHORT).show();
						}	
					}
				}
			});
			
			//handling resetting ears (Nabaztag)
			Button buttonResetEars = (Button) findViewById(R.id.ButtonOreille);
			buttonResetEars.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					// TODO Auto-generated method stub
					//writing xml
					String xml = XmlWriter.writeXmlForResettingEars((String) selectedObject.get("idDevice"));

					//calling the webservice
					String xmlResponse = SendXml.sendXmlToServer(xml);	

					String name = (String) selectedObject.get("name");

					ArrayList<String> temp = XmlParser.parseGeneralGetMsgAndComment(xmlResponse);
					String comment = temp.get(1);

					//Toast.makeText(getApplicationContext(), name + "'s ears have been resetted.", Toast.LENGTH_SHORT).show();				
					Toast.makeText(getApplicationContext(), name + ": " + comment, Toast.LENGTH_SHORT).show();				
				}
			});

			//handling waking up the Nabaztag
			Button buttonWakeUp = (Button) findViewById(R.id.ButtonWakeUp);
			buttonWakeUp.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					// TODO Auto-generated method stub
					String xml = XmlWriter.writeXmlForWakeUp((String) selectedObject.get("idDevice"));
					String xmlResponse = SendXml.sendXmlToServer(xml);	//Not used for now

					String name = (String) selectedObject.get("name");


					ArrayList<String> response = XmlParser.parseGeneralGetMsgAndComment(xmlResponse);
					String comment = response.get(1);

					Toast.makeText(getApplicationContext(), name + ": " + comment, Toast.LENGTH_SHORT).show();	

				}
			});

			//handling checking if the Nabaztag is asleep
			Button buttonIsSleeping = (Button) findViewById(R.id.ButtonIsSleeping);
			buttonIsSleeping.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					// TODO Auto-generated method stub
					String xml = XmlWriter.writeXmlForIsSleeping((String) selectedObject.get("idDevice"));
					String xmlResponse = SendXml.sendXmlToServer(xml);	//Not used for now

					String name = (String) selectedObject.get("name");

					ArrayList<String> response = XmlParser.parseIsSleepingResponse(xmlResponse);
					String status = response.get(0);

					Toast.makeText(getApplicationContext(), name + "'s wake up status: "+ status, Toast.LENGTH_SHORT).show();
					//Toast.makeText(getApplicationContext(), xmlResponse, Toast.LENGTH_SHORT).show();				
				}
		});
		
		// handling sending a song (Nabaztag)
			Button buttonSong = (Button) findViewById(R.id.ButtonSong);
			buttonSong.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					// TODO Auto-generated method stub
					actionDialogPourBntSong();
				}
			});
			
		//handling sending a static choregraphy (Nabaz)
		Button buttonChor =(Button) findViewById(R.id.ButtonDanceNabaztag);
		buttonChor.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				String xml = XmlWriter.writeXmlForSendingAStaticChoregraphy((String) selectedObject.get("idDevice"));
				String xmlResponse = SendXml.sendXmlToServer(xml);	//Not used for now

				String name = (String) selectedObject.get("name");

				ArrayList<String> response = XmlParser.parseGeneralGetMsgAndComment(xmlResponse);
				String comment = response.get(1);

				Toast.makeText(getApplicationContext(), name + ": "+ comment, Toast.LENGTH_SHORT).show();
				//Toast.makeText(getApplicationContext(), xmlResponse, Toast.LENGTH_SHORT).show();				
			}
	});
		
		//handling making a Nabaz sleep
		Button buttonMakeSleep =(Button) findViewById(R.id.ButtonMakeSleep);
		buttonMakeSleep.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				String xml = XmlWriter.writeXmlForMakeSleep((String) selectedObject.get("idDevice"));
				String xmlResponse = SendXml.sendXmlToServer(xml);	//Not used for now

				String name = (String) selectedObject.get("name");

				ArrayList<String> response = XmlParser.parseGeneralGetMsgAndComment(xmlResponse);
				String comment = response.get(1);

				Toast.makeText(getApplicationContext(), name + ": "+ comment, Toast.LENGTH_SHORT).show();
				//Toast.makeText(getApplicationContext(), xmlResponse, Toast.LENGTH_SHORT).show();				
			}
	});
		

	}

		/**
		 * *************************************************************
		 * MYDESKFRIEND
		 * *************************************************************
		 */	
		if(((String) selectedObject.get("deviceType")).equalsIgnoreCase("MyDeskFriend")){
			setContentView(R.layout.action_mydeskfriend);

			//handling sending a message(mydeskfriend)

			Button buttonSendMessageMydeskfriend = (Button) findViewById(R.id.ButtonMessage_mydeskfriend);
			buttonSendMessageMydeskfriend.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					// TODO Auto-generated method stub

					String text = ((EditText) findViewById(R.id.EditText_mydeskfriend)).getText().toString();

					//writing xml
					String xml = XmlWriter.writeXmlForSendingMessage(
							(String) selectedObject.get("idDevice"), 
							text);
					//calling the webservice
					String xmlResponse = SendXml.sendXmlToServer(xml);
					String name = (String) selectedObject.get("name");
					
					ArrayList<String> temp = XmlParser.parseGeneralGetMsgAndComment(xmlResponse);
					String comment = temp.get(1);
					Toast.makeText(getApplicationContext(), name +": "+comment, Toast.LENGTH_SHORT).show();			
				}
			});

		}		

	}
	// Regular Expression, regular le adresse URL
	private boolean checkString(String s) {
		return s.matches("[a-zA-z]+://[^/s]*");
	}

	
	//action button song
	public void actionDialogPourBntSong() {
		final EditText e = new EditText(this);
		
		SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
		String lastValue = prefs.getString("streamLink", "");
		e.setText(lastValue);
		
		new AlertDialog.Builder(this)
				.setTitle("URL")
				.setIcon(R.drawable.musicicon)
				.setView(e)
				.setPositiveButton(" Ok ",
						new DialogInterface.OnClickListener() {
					
					
					
							public void onClick(DialogInterface dialog, int id) {
								if (checkString(e.getText().toString())) {
									String text = (e.getText().toString());
									
									//put last link in preferences
									SharedPreferences lastLink = getSharedPreferences(PREFS_NAME, 0);
									SharedPreferences.Editor editor = lastLink.edit();
									editor.putString("streamLink", text);
									editor.commit();
									
									
									String name = (String) selectedObject
											.get("name");

									// writing xml
									String xml = XmlWriter.writeXmlForPlayURL( (String) selectedObject.get("idDevice"), text);
													

									// calling the webservice
									String xmlResponse = SendXml
											.sendXmlToServer(xml);

									ArrayList<String> temp = XmlParser
											.parseGeneralGetMsgAndComment(xmlResponse);
									String comment = temp.get(1);

									Toast.makeText(getApplicationContext(),
											name + ": " + comment,
											Toast.LENGTH_SHORT).show();

								} else {
									new AlertDialog.Builder(e.getContext())
											.setMessage("URL is not correct")
											.setPositiveButton(
													"Yes",
													new DialogInterface.OnClickListener() {
														public void onClick(
																DialogInterface dialog,
																int id) {
															actionDialogPourBntSong();
														}
													}).show();

								}
							}
						}).show();
	}
	
	
	// action pour menu

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		 
		LayoutInflater  factory = LayoutInflater.from(this);
		final View textEntryView = factory.inflate(R.layout.dialog_about, null);
		 
		switch (item.getItemId()) {
		case R.id.menulogin:
			// about function
			if (SmartObjects.SMART_OBJECTS_LIST.isEmpty()) {
				Intent intent = new Intent();
				intent.setClass(Action.this, SobjalMain.class);
				startActivity(intent);
			} else {
				Intent intent = new Intent();
				intent.setClass(Action.this, login.class);
				startActivity(intent);
			}
			return true;
		case R.id.menulogoff:
			// settings function
			new AlertDialog.Builder(this)
					.setMessage("Are you sure you want to exit?")
					.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									SmartObjects.SMART_OBJECTS_LIST = null;
									Intent intent = new Intent();
									intent.setClass(Action.this,
											SobjalMain.class);
									startActivity(intent);
									Action.this.finish();
								}
							})
					.setNegativeButton("No",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							}).show();
			return true;
		case R.id.menuabout:
			
			new AlertDialog.Builder(this)
			.setMessage("About")
			.setIcon(android.R.drawable.ic_menu_info_details)
			.setView(textEntryView).show();
		default:
			Log.e("Unknown menu item selected", " ");
			return false;
		}
	}
}
